package com.qh.resourcehub.program.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qh.resourcehub.program.access.service.AccessExamineService;
import com.qh.resourcehub.program.audit.service.SourceCodeAuditExamineService;
import com.qh.resourcehub.program.dto.*;
import com.qh.resourcehub.program.entity.OperationalSupportEntity;
import com.qh.resourcehub.program.entity.UserEntity;
import com.qh.resourcehub.program.firewall.service.FirewallExamineService;
import com.qh.resourcehub.program.mapper.OperationalSupportMapper;
import com.qh.resourcehub.program.mapper.UserInfoMapper;
import com.qh.resourcehub.program.netmapping.service.NetMappingExamineService;
import com.qh.resourcehub.program.security.service.SecurityAssessmentExamineService;
import com.qh.resourcehub.program.user.service.UserInfoService;
import com.qh.resourcehub.program.virtual.service.VirtualExamineService;
import com.qh.resourcehub.program.vo.*;
import com.qh.resourcehub.program.vpn.service.VpnExamineService;
import com.qh.resourcehub.program.wifi.service.WifiExamineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Y6
 * @date: 2025/4/18 16:22
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private OperationalSupportMapper operationalSupportMapper;
    @Autowired
    private VirtualExamineService virtualExamineService;

    @Autowired
    private WifiExamineService wifiExamineService;
    @Autowired
    private VpnExamineService vpnExamineService;

    @Autowired
    private FirewallExamineService firewallExamineService;
    @Autowired
    private NetMappingExamineService netMappingExamineService;
    @Autowired
    private AccessExamineService accessExamineService;
    @Autowired
    private SourceCodeAuditExamineService sourceCodeAuditExamineService;
    @Autowired
    private SecurityAssessmentExamineService securityAssessmentExamineService;
    @Override
    public UserVo queryUserInfo(UserDto userDto) {
        List<UserVo> dataList=userInfoMapper.queryUserInfo(userDto);
        UserVo userVo = dataList.get(0);
        return userVo;
    }

    @Override
    public List<UserVo> queryUserLeaderInfo(UserDto userDto) {
        return userInfoMapper.queryUserLeaderInfo(userDto);
    }

    /**
     * 查询用户支持信息
     * 
     * @param userDto 用户查询参数
     *                - getInfoType: 当前资料的编码，例如：123456
     *                - getType: 部门类型标识，1-数据服务室，2-运维保障室
     * @return 用户信息列表
     */
    @Override
    public List<UserVo> queryUserSupportInfo(UserDto userDto) {
        //先查询当前用户信息\ //判断当前状态（状态码必穿）
        List<UserVo> dataList= userInfoMapper.queryUserInfo(userDto);
        UserVo userData = dataList.get(0);
        if ("00".equals(userDto.getProcessStatus())){
            if ("6".equals(userDto.getInfoType())||"7".equals(userDto.getInfoType())||"8".equals(userDto.getInfoType())){
                List<UserVo> userVos = userInfoMapper.queryInfoBySJ();
                return userVos;
            }else {
                //01就需要传用户id+部门id，查询申请人所在单位领导列表
                userDto.setOrgCode(userData.getParentCode());
                if (userData.getOfficerole().contains(",")){
                    String[] split = userData.getOfficerole().split(",");
                    String leaderId = split[0];
                    Double v = Double.valueOf(leaderId);
                    if (v>6){
                        //就查询处级干部
                        return userInfoMapper.queryDeptByCJ(userDto);
                    }else {
                        //就查询更高级
                        return userInfoMapper.queryDeptBySJ(userDto);
                    }
                }else {
                    Double v = Double.valueOf(userData.getOfficerole());
                    if (v>6){
                        //就查询处级干部
                        return userInfoMapper.queryDeptByCJ(userDto);
                    }else {
                        //就查询更高级
                        return userInfoMapper.queryDeptBySJ(userDto);
                    }
                }
            }
        } else if ("01".equals(userDto.getProcessStatus())&&  "1".equals(userDto.getType())) {
            //02不需要传其他信息，直接查询信息中心科室领导列表 运行保障室
            //先查询张加男
            UserDto userDtos=new UserDto();
            userDtos.setUserCode("71C322BB53AD4010E0530A0141374010");
            List<UserVo> userVoList = userInfoMapper.queryUserInfo(userDtos);
            UserVo userVo = userVoList.get(0);
            List<UserVo> userVos = userInfoMapper.queryInfoByBZ();
            userVos.add(userVo);
            return userVos;
        } else if ("01".equals(userDto.getProcessStatus()) &&  "2".equals(userDto.getType())) {
            //02不需要传其他信息，直接查询信息中心科室领导列表数据服务室
            List<UserVo> userVos = userInfoMapper.queryInfoBySJ();
            return userVos;
        } else if ("02".equals(userDto.getProcessStatus())) {
            if ("2".equals(userDto.getInfoType())||"6".equals(userDto.getInfoType())||"7".equals(userDto.getInfoType())||"8".equals(userDto.getInfoType())){
                //d5103409-2757-4f94-b7a1-fce32c490587
                userDto.setUserCode("d5103409-2757-4f94-b7a1-fce32c490587");
                return userInfoMapper.queryUserInfo(userDto);
            }else {
                //03不需要传其他信息，直接查询信息中心领导列表
                return userInfoMapper.queryInfoByLD();
            }
        } else if ("03".equals(userDto.getProcessStatus())) {
            //04不需要传其他信息，直接查询观测与网络处领导列表
            return userInfoMapper.queryInfoByGCYWL();
        } else if ("04".equals(userDto.getProcessStatus())) {
            if ("3".equals(userDto.getInfoType())){
                //d5103409-2757-4f94-b7a1-fce32c490587
                userDto.setUserCode("d5103409-2757-4f94-b7a1-fce32c490587");
                return userInfoMapper.queryUserInfo(userDto);
            }else {
                //05不需要传其他信息，直接查询信息中心值班人员列表
                List<UserVo> result=new ArrayList<>();
                //查询指定的运行保障室用户
                //王宝忠	A51132AA65F04E6A915F1B4261CCC1BE
                //张嘉男	71C322BB53AD4010E0530A0141374010
                //阿成凤	7a900209-a0e7-4581-b5d2-6bd2277ace74
                //胡单辉	ef398a80-fac6-430e-92aa-a15fddc2f218
                //马媛	a26fe150-0a35-4dcc-afad-fd8820599133
                //郭宝凯	bf92a137-7a14-42c2-ada4-a94aada1a4b3
                List<OperationalSupportEntity> operationalSupportEntities = operationalSupportMapper.selectList(null);
                for (OperationalSupportEntity operationalSupportEntity : operationalSupportEntities) {
                    UserDto userDtos=new UserDto();
                    userDtos.setUserCode(operationalSupportEntity.getUserCode());
                    List<UserVo> userVoList = userInfoMapper.queryUserInfo(userDtos);
                    UserVo userVo = userVoList.get(0);
                    result.add(userVo);
                }
                return result;
            }
        }
        return null;
    }

    @Override
    public UserTodoSummaryVO queryUserRepresentativeNum(UserDto userDto) {
        String userCode = userDto.getUserCode();

        // 初始化待办统计列表
        List<FlowTodoCountVO> todoCounts = new ArrayList<>();

        // 查询虚拟机审批待办
        VirtualDto virtualDto = new VirtualDto();
        virtualDto.setUserCode(userCode);
        List<VirtualVo> virtualVos = virtualExamineService.queryVirtualExamineDataNum(virtualDto);
        int virtualCount = (virtualVos != null) ? virtualVos.size() : 0;
        todoCounts.add(new FlowTodoCountVO("virtual", "虚拟机审批", virtualCount));

        // 查询 WiFi 审批待办
        WifiDto wifiDto = new WifiDto();
        wifiDto.setUserCode(userCode);
        List<WifiVo> wifiVos = wifiExamineService.queryWifiExamineDataNum(wifiDto);
        int wifiCount = (wifiVos != null) ? wifiVos.size() : 0;
        todoCounts.add(new FlowTodoCountVO("wifi", "WiFi 审批", wifiCount));
        //VPN代办
        VpnDto vpnDto = new VpnDto();
        vpnDto.setUserCode(userCode);
        List<VpnVo> vpnVos = vpnExamineService.queryVpnExamineDataNum(vpnDto);
        int vpnCont = (vpnVos != null) ? vpnVos.size() : 0;
        todoCounts.add(new FlowTodoCountVO("vpn", "VPN 审批", vpnCont));

        FirewallDto firewallDto = new FirewallDto();
        firewallDto.setUserCode(userCode);
        List<FirewallVo> firewallVos = firewallExamineService.queryFirewallExamineDataNum(firewallDto);
        int FirewallCont = (firewallVos != null) ? firewallVos.size() : 0;
        todoCounts.add(new FlowTodoCountVO("firewall", "firewall 审批", FirewallCont));

        NetMappingDto netMappingDto = new NetMappingDto();
        netMappingDto.setUserCode(userCode);
        List<NetMappingVo> netMappingVos = netMappingExamineService.queryNetMappingExamineDataNum(netMappingDto);
        int netMappingCont =   (netMappingVos != null) ? netMappingVos.size() : 0;
        todoCounts.add(new FlowTodoCountVO("netMapping", "netMapping 审批", netMappingCont));

        // 查询Access审批待办
        AccessDto accessDto = new AccessDto();
        accessDto.setUserCode(userCode);
        List<AccessVo> accessVos = accessExamineService.queryAccessExamineDataNum(accessDto);
        int accessCount = (accessVos != null) ? accessVos.size() : 0;
        todoCounts.add(new FlowTodoCountVO("access", "Access审批", accessCount));

        // 查询源代码安全评估审计报告审批待办
        SourceCodeAuditDto sourceCodeAuditDto = new SourceCodeAuditDto();
        sourceCodeAuditDto.setUserCode(userCode);
        List<SourceCodeAuditVo> sourceCodeAuditVos = sourceCodeAuditExamineService.querySourceCodeAuditExamineDataNum(sourceCodeAuditDto);
        int sourceCodeAuditCount = (sourceCodeAuditVos != null) ? sourceCodeAuditVos.size() : 0;
        todoCounts.add(new FlowTodoCountVO("sourceCodeAudit", "源代码安全评估审计报告审批", sourceCodeAuditCount));

        // 查询安全风险评估检查报告审批待办
        SecurityAssessmentDto securityAssessmentDto = new SecurityAssessmentDto();
        securityAssessmentDto.setUserCode(userCode);
        List<SecurityAssessmentVo> securityAssessmentVos = securityAssessmentExamineService.querySecurityAssessmentExamineDataNum(securityAssessmentDto);
        int securityAssessmentCount = (securityAssessmentVos != null) ? securityAssessmentVos.size() : 0;
        todoCounts.add(new FlowTodoCountVO("securityAssessment", "安全风险评估检查报告审批", securityAssessmentCount));

        // 封装返回结果
        UserTodoSummaryVO result = new UserTodoSummaryVO();
        result.setTodoCounts(todoCounts);
        return result;
    }

    @Override
    public String pushToMenuSystem(String userCode) {
        if (ObjectUtil.isEmpty(userCode)) {
            return "userCode不能为空";
        }
        if (userCode.equals("all")) {
            List<UserEntity> userEntities = userInfoMapper.selectList(null);
            for (UserEntity userEntity : userEntities) {
                UserDto userDto = new UserDto();
                userDto.setUserCode(userEntity.getUserCode());
                List<UserVo> userInfo = userInfoMapper.queryUserInfo(userDto);
                if (userInfo == null || userInfo.size() == 0) {
                    continue;
                }
                String deptCode = "";
                String orgCode = userInfo.get(0).getOrgCode();
                if (userInfo.size() > 1) {
                    StringBuilder sb = new StringBuilder();
                    for (UserVo userVo : userInfo) {
                        sb.append(userVo.getCode()).append(",");
                    }
                    // 去掉最后一个逗号
                    deptCode = sb.substring(0, sb.length() - 1);
                } else {
                    deptCode = userInfo.get(0).getCode();
                }
                // 构造请求体
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("sysName", "青海省气象局基础资源申请系统");
                requestBody.put("sysCode", "057003");
                requestBody.put("userCode", userInfo.get(0).getUserCode());
                requestBody.put("deptCode", deptCode);
                requestBody.put("orgCode", orgCode);
                requestBody.put("url", "http://10.181.23.237:9992/");
                requestBody.put("data", "");
                try {
                    RestTemplate restTemplate = new RestTemplate();
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

                    ResponseEntity<String> response = restTemplate.postForEntity(
                            "http://10.1.65.76:7001/app-menu/saveMenusInfo.action",
                            entity,
                            String.class
                    );
                    ObjectMapper objectMapper = new ObjectMapper();
                    Map<String, Object> respBody = objectMapper.readValue(response.getBody(), Map.class);
                    String stateFlag = (String) respBody.get("stateFlag");
                    String msg = (String) respBody.get("msg");
                } catch (JsonProcessingException e) {
                    System.out.println("当前用户推送失败"+userEntity.getName());
                }
            }
            return "推送成功 ";
        } else {
            // 查询用户信息
            UserDto userDto = new UserDto();
            userDto.setUserCode(userCode);
            List<UserVo> userInfo = userInfoMapper.queryUserInfo(userDto);
            if (userInfo == null || userInfo.size() == 0) {
                return "未查到用户的部门或机构信息";
            }
            String deptCode = "";
            String orgCode = userInfo.get(0).getOrgCode();
            if (userInfo.size() > 1) {
                StringBuilder sb = new StringBuilder();
                for (UserVo userVo : userInfo) {
                    sb.append(userVo.getCode()).append(",");
                }
                // 去掉最后一个逗号
                deptCode = sb.substring(0, sb.length() - 1);
            } else {
                deptCode = userInfo.get(0).getCode();
            }
            // 构造请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("sysName", "青海省气象局基础资源申请系统");
            requestBody.put("sysCode", "057003");
            requestBody.put("userCode", userCode);
            requestBody.put("deptCode", deptCode);
            requestBody.put("orgCode", orgCode);
            requestBody.put("url", "http://10.181.23.237:9992/");
            requestBody.put("data", "");
            try {
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

                ResponseEntity<String> response = restTemplate.postForEntity(
                        "http://10.1.65.76:7001/app-menu/saveMenusInfo.action",
                        entity,
                        String.class
                );
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> respBody = objectMapper.readValue(response.getBody(), Map.class);
                String stateFlag = (String) respBody.get("stateFlag");
                String msg = (String) respBody.get("msg");
                if ("01".equals(stateFlag)) {
                    return "推送成功: " + (msg == null ? "无提示信息" : msg);
                } else {
                    return "推送失败: " + (msg == null ? "接口未返回错误信息" : msg);
                }

            } catch (Exception e) {
                e.printStackTrace();
                return "推送失败: " + e.getMessage();
            }
        }
    }

}
